/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Linq;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    public class CombineTableBindings
    {
        private static ScrollViewer scrollViewerOpenTables;
        private static ScrollViewer scrollViewerOpenTables2;

        private static int userScrollIndex = 0;
        private static int userScrollIndex2 = 0;

        /// <summary>
        /// 
        /// </summary>
        public static ORDER SelectedTable = null;
        public static ORDER SelectedTable2 = null;
        public static USER SelectedLeftUser = null;
        public static USER SelectedRightUser = null;


        /// <summary>
        /// 
        /// </summary>
        public static void Init()
        {
            CombineTablesWindow.OpenTables.SelectionChanged +=
                new SelectionChangedEventHandler(listViewCustTicket_SelectionChanged_NOTHROW);

            CombineTablesWindow.OpenTables2.SelectionChanged +=
                new SelectionChangedEventHandler(listViewCustTicket2_SelectionChanged_NOTHROW);

            CombineTablesWindow.ExitButton.MouseDown += new MouseButtonEventHandler(cancelButton_MouseDown_NOTHROW);
            CombineTablesWindow.ScrollUserLeft.MouseDown += new MouseButtonEventHandler(userLeft_MouseDown_NOTHROW);
            CombineTablesWindow.ScrollUserLeft2.MouseDown += new MouseButtonEventHandler(userLeft2_MouseDown_NOTHROW);
            CombineTablesWindow.ScrollUserRight.MouseDown += new MouseButtonEventHandler(userRight_MouseDown_NOTHROW);
            CombineTablesWindow.ScrollUserRight2.MouseDown += new MouseButtonEventHandler(userRight2_MouseDown_NOTHROW);
        }

        public static ScrollViewer ScrollViewerOpenTables
        {
            get { return scrollViewerOpenTables; }
            set { scrollViewerOpenTables = value; }
        }

        public static ScrollViewer ScrollViewerOpenTables2
        {
            get { return scrollViewerOpenTables2; }
            set { scrollViewerOpenTables2 = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static ScrollViewer FindScroll()
        {
            ScrollViewer sv = null;
            Border scroll_border = VisualTreeHelper.GetChild(CombineTablesWindow.OpenTables, 0) as Border;

            if (scroll_border is Border)
            {
                scrollViewerOpenTables = scroll_border.Child as ScrollViewer;

                if (scrollViewerOpenTables is ScrollViewer)
                {
                    sv = scrollViewerOpenTables;
                }
            }
            return sv;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static ScrollViewer FindScroll2()
        {
            ScrollViewer sv = null;

            Border scroll_border = VisualTreeHelper.GetChild(CombineTablesWindow.OpenTables2, 0) as Border;

            if (scroll_border is Border)
            {
                scrollViewerOpenTables2 = scroll_border.Child as ScrollViewer;

                if (scrollViewerOpenTables2 is ScrollViewer)
                {
                    sv = scrollViewerOpenTables2;
                }
            }

            return sv;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void userLeft_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            userScrollIndex--;
            CombineTablesWindow.ListSelectedTable.SelectedItem = null;
            CombineTablesWindow.ListSelectedTable.ItemsSource = null;
            Refresh();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void userLeft2_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            userScrollIndex2--;
            CombineTablesWindow.ListSelectedTable2.SelectedItem = null;
            CombineTablesWindow.ListSelectedTable2.ItemsSource = null;
            Refresh();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void userRight_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            userScrollIndex++;
            CombineTablesWindow.ListSelectedTable.SelectedItem = null;
            CombineTablesWindow.ListSelectedTable.ItemsSource = null;
            Refresh();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void userRight2_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            userScrollIndex2++;
            CombineTablesWindow.ListSelectedTable2.SelectedItem = null;
            CombineTablesWindow.ListSelectedTable2.ItemsSource = null;
            Refresh();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void listViewCustTicket_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.Count != 0)
                {
                    SelectedTable = e.AddedItems[0] as ORDER;
                    List<ORDER> listOneItemList = new List<ORDER>(1);
                    listOneItemList.Add(SelectedTable);
                    CombineTablesWindow.ListSelectedTable.ItemsSource = listOneItemList;

                    ///Make the xfer button recheck to see if it should be visible.
                    PosWindow.RefreshVisibility(PosWindow.PROP_TYPE_ENUM.COM);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void listViewCustTicket2_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.Count != 0)
                {
                    SelectedTable2 = e.AddedItems[0] as ORDER;
                    List<ORDER> listOneItemList = new List<ORDER>(1);
                    listOneItemList.Add(SelectedTable2);
                    CombineTablesWindow.ListSelectedTable2.ItemsSource = listOneItemList;

                    ///Make the xfer button recheck to see if it should be visible.
                    PosWindow.RefreshVisibility(PosWindow.PROP_TYPE_ENUM.COM);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void cancelButton_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            try
            {
                Oceanside.ControlPanelWindow.Show();
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }


        public static void PrepareForScreenChange_NOTHROW()
        {
            try
            {
                userScrollIndex = 0;
                userScrollIndex2 = 0;
                SelectedTable = null;
                SelectedTable2 = null;
                SelectedLeftUser = null;
                SelectedRightUser = null;
                CombineTablesWindow.ListSelectedTable.SelectedItem = null;
                CombineTablesWindow.ListSelectedTable.ItemsSource = null;
                CombineTablesWindow.ListSelectedTable2.SelectedItem = null;
                CombineTablesWindow.ListSelectedTable2.ItemsSource = null;

                CombineTablesWindow.OpenTables.SelectedItem = null;
                CombineTablesWindow.OpenTables2.SelectedItem = null;

                ///Make the xfer button recheck to see if it should be visible.
                PosWindow.RefreshVisibility(PosWindow.PROP_TYPE_ENUM.COM);

                Refresh();

            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, ex);
            }
        }

        /// <summary>
        /// Assure the GUI displays properly.  This will update the visibility of buttons and etc.
        /// </summary>
        public static void Refresh()
        {
            ///Select all users that can order food and have an employee shift open right now.
            ///We cannot transfer a table to someone that has not clocked in yet.
            BUSINESS_DAY bd = BUSINESS_DAY.GetNow(SHIFT.GlobalContext);
            var q = from U in SHIFT.GlobalContext.USERS
                    where U.ROLES.Where(R => R.ACCESS_LEVEL.CanOrder == true).Count() != 0
                    join es in SHIFT.GlobalContext.SHIFTS.Where(s => s.IsComplete == false && s.NavBusinessDayId == bd.Id) on U.Id equals es.UserId
                    select U;

            List<USER> usersList;
            if (q.Any())
            {
                usersList = q.ToList();
                ///First bounds check the scroll indices for too high, wrap if it is.
                if (userScrollIndex >= usersList.Count)
                {
                    userScrollIndex = 0;
                }
                if (userScrollIndex2 >= usersList.Count)
                {
                    userScrollIndex2 = 0;
                }

                ///Bounds check the scroll indices for too low, wrap if it is.
                if (userScrollIndex < 0)
                {
                    userScrollIndex = usersList.Count - 1;
                }
                if (userScrollIndex2 < 0)
                {
                    userScrollIndex2 = usersList.Count - 1;
                }

                ///Handle the left side
                USER leftUser = usersList[userScrollIndex];

                List<ORDER> leftUsersOrders = SHIFT.GlobalContext.ORDERS.Where(o => !o.IsClosed &&
                    ((o.ReopenByUserId != null && o.ReopenByUserId == leftUser.Id) || (o.ReopenByUserId == null && o.UserId == leftUser.Id))).ToList();

                CombineTablesWindow.OpenTables.SelectedItem = null;
                CombineTablesWindow.OpenTables.ItemsSource = leftUsersOrders;
                CombineTablesWindow.TextBlockuserName.DataContext = leftUser;
                SelectedLeftUser = leftUser;

                if (CombineTablesWindow.OpenTables.ItemsSource != null)
                {
                    CombineTablesWindow.OpenTables.Items.Refresh();
                }

                USER rightUser = usersList[userScrollIndex2];
                List<ORDER> rightUsersOrders = SHIFT.GlobalContext.ORDERS.Where(o => !o.IsClosed &&
                    ((o.ReopenByUserId != null && o.ReopenByUserId == rightUser.Id) || (o.ReopenByUserId == null && o.UserId == rightUser.Id))).ToList();

                CombineTablesWindow.OpenTables2.SelectedItem = null;
                CombineTablesWindow.OpenTables2.ItemsSource = rightUsersOrders;
                CombineTablesWindow.TextBlockuserName2.DataContext = rightUser;
                SelectedRightUser = rightUser;

                if (CombineTablesWindow.OpenTables2.ItemsSource != null)
                {
                    CombineTablesWindow.OpenTables2.Items.Refresh();
                }
            }
        }
    }
}
